package com.chenguo.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chenguo.reggie.common.BaseContext;
import com.chenguo.reggie.common.R;
import com.chenguo.reggie.dto.OrdersDto;
import com.chenguo.reggie.pojo.OrderDetail;
import com.chenguo.reggie.pojo.Orders;
import com.chenguo.reggie.pojo.ShoppingCart;
import com.chenguo.reggie.pojo.User;
import com.chenguo.reggie.service.OrderDetailService;
import com.chenguo.reggie.service.OrderService;
import com.chenguo.reggie.service.ShoppingCartService;
import com.chenguo.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        orderService.submit(orders);

        return R.success("下单成功");
    }

    /**
     * 后台的订单数据
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, Long number, Date beginTime, Date endTime) {
        // 创建基本page
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        // 定制有名字的特殊orders
        Page<OrdersDto> ordersDtoPage = new Page<>();

        // 添加条件查询 使用动态SQL
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.like(number != null, Orders::getId, number)
                                .gt(beginTime != null, Orders::getOrderTime, beginTime)
                                .lt(endTime != null, Orders::getOrderTime, endTime);

        orderService.page(pageInfo, ordersLambdaQueryWrapper);

        // 拷贝pageInfo
        BeanUtils.copyProperties(pageInfo, ordersDtoPage, "records");

        // 获取记录数
        List<Orders> records = pageInfo.getRecords();

        List<OrdersDto> ordersDtoList = records.stream().map((item) -> {
            // 新建一个容器
            OrdersDto ordersDto = new OrdersDto();

            BeanUtils.copyProperties(item, ordersDto);

            // 获取用户id
            Long userId = item.getUserId();
            // 查询这个用户对象，因为用户是根据电话号码注册的，所以用户名是空的
            User user = userService.getById(userId);
            ordersDto.setUserName(user.getName());
            return ordersDto;
        }).collect(Collectors.toList());

        // 填充ordersDtoPage的records
        ordersDtoPage.setRecords(ordersDtoList);

        return R.success(ordersDtoPage);
    }

    /**
     * 订单状态修改
     * @param map
     * @return
     */
    @PutMapping
    public R<String> orderStatusChange(@RequestBody Map<String, String> map) {
        String id = map.get("id");
        Long orderId = Long.parseLong(id);
        Integer status = Integer.parseInt(map.get("status"));

        if (orderId == null || status == null) {
            return R.error("传入的信息不合法");
        }
        Orders orders = orderService.getById(orderId);
        orders.setStatus(status);
        orderService.updateById(orders);
        return R.success("订单状态修改成功");
    }

    /**
     * 查看订单的记录
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> pagePhone(int page, int pageSize) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();

        // 获取当前用户的id
        Long currentId = BaseContext.getCurrentId();

        // 构建条件构造器
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId, currentId);
        ordersLambdaQueryWrapper.orderByDesc(Orders::getOrderTime);

        orderService.page(pageInfo, ordersLambdaQueryWrapper);

        // 拷贝查询出来的值
        BeanUtils.copyProperties(pageInfo, ordersDtoPage, "records");

        // 获取订单
        List<Orders> records = pageInfo.getRecords();

        List<OrdersDto> ordersDtoList = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);

            // 获取订单ID
            Long id = item.getId();

            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, id);
            long count = orderDetailService.count(orderDetailLambdaQueryWrapper);

            List<OrderDetail> list = orderDetailService.list(orderDetailLambdaQueryWrapper);
            ordersDto.setSumNum(count);
            ordersDto.setOrderDetails(list);
            return ordersDto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(ordersDtoList);
        return R.success(ordersDtoPage);
    }

    /**
     * 用户端点击再来一单
     * 用户端点击再来一单是直接跳转到购物车的，所以为了避免数据有问题，再跳转之前需要吧购物车的数据清除
     *  1 通过orderId获取订单明细
     *  2 把订单明细的数据传到购物车表中，不过在此之前要先把购物车表中的数据给清除了（当前用户的）
     *
     * @param map
     * @return
     */
    @PostMapping("/again")
    public R<String> againSubmit(@RequestBody Map<String, String> map) {
        String temp_id = map.get("id");

        long id = Long.parseLong(temp_id);
        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, id);

        // 获取订单对应的所有订单明细
        List<OrderDetail> list = orderDetailService.list(orderDetailLambdaQueryWrapper);

        // 清理购物车
        shoppingCartService.clean();

        // 获取用户id
        Long currentId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = list.stream().map((item) -> {
            // 把从order表中和order_details表中获取到的数据赋值给购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(currentId);
            shoppingCart.setImage(item.getImage());

            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            if (dishId != null) {
                // 是菜品
                shoppingCart.setDishId(dishId);
            } else {
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        // 把携带数据的购物车批量插入购物车表中
        shoppingCartService.saveBatch(shoppingCartList);

        return R.success("操作成功");
    }

}
